import { ChangeEvent, useEffect, useState } from 'react';
import {useNavigate} from 'react-router-dom';
import styleModule from './login.module.scss';
import './index.less';
import initLoginBg from './init.js';
import { Space, Input, Button,message } from 'antd';
import {useSelector,useDispatch} from 'react-redux';
import {captchaImgApi,loginApi} from '@/request/api';
import users from '@/store/users'
import store2 from 'store2';

const View = () => {
    const dispatch = useDispatch();
    const  navigate = useNavigate();
    const [passwordVisible, setPasswordVisible] = useState(false);
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [captchcode, setCaptchcode] = useState("");
    const [captchImg, setCaptchImg] = useState("");
    const [uuid, setUuid] = useState("");

    useEffect(() => {
        initLoginBg();
        getCaptchaImg();
        window.onresize = function () {
            initLoginBg();
        }
    }, [])



    // 收集用户信息
    const eventChange = (e: ChangeEvent<HTMLInputElement>, func: string) => {
        let value = e.target.value;
        switch (func) {
            case 'setUsername':
                setUsername(value);
                break;
            case 'setPassword':
                setPassword(value);
                break;
            case 'setCaptchcode':
                setCaptchcode(value);
                break;
            default:
                break;
        }
    }

    // 跳转注册页面
    const goRegister = () =>{
        navigate('/register');
    }


    // 提交表单信息
    const onsubmitBtn = async() =>{
        if(!username.trim()) return;
        if(!password.trim()) return;
        if(!captchcode.trim() && captchcode.length != 6) return;

        console.log(username,password,captchcode);
        const data = {
            username,
            password,
            uuid,
            captchcode
        }
        // dispatch(users.asyncActions.asyncLogin(data));
        const res = await loginApi(data);
        console.log(res);
        if(res.data.code == 200){
            message.info('登录成功');
            // 存储token
            store2('setToken',res.data.token);
            // 存到redux中
            dispatch({ type: 'setToken', val: res.data.token });
            // 跳转
            navigate('/');
        }
        
    }

    // 获取验证
    const getCaptchaImg = async() =>{
        let res = await captchaImgApi();
        let datas = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(res.data.dataImg)))
        setCaptchImg(datas);
        setUuid(res.data.uuid);
        setCaptchcode(res.data.text);
    }



    return (
        <div className={styleModule.loginPage + ' loginpage'}>
            {/* 背景 */}
            <canvas id="canvas" style={{ backgroundColor: '#000' }}></canvas>
            {/* 登录模块 */}
            <div className={styleModule.loginBox}>
                <div className={styleModule.title}>
                    <h1>前端糖小梁&nbsp;•&nbsp;糖小梁后台系统</h1>
                    <p>登录</p>
                </div>
                {/* 登录表单 */}
                <Space direction="vertical" size="large" style={{ display: 'flex' }}>
                    <Input placeholder="输入账号" onChange={(e) => eventChange(e, 'setUsername')} />
                    <Input.Password
                        onChange={(e) => eventChange(e, 'setPassword')}
                        placeholder="输入密码"
                        visibilityToggle={{ visible: passwordVisible, onVisibleChange: setPasswordVisible }}
                    />
                    <div className='captchBox' >
                        <Input placeholder="输入验证码" onChange={(e) => eventChange(e, 'setCaptchcode')} />
                        <img className='catchaimg' height="28" src={captchImg} alt='验证码' onClick={getCaptchaImg} />
                    </div>
                    <div>
                        <span>还没有账号?</span>
                        <Button type='link' onClick={goRegister}>去注册</Button>
                    </div>
                    <Button type="primary" className='loginBtn' block onClick={onsubmitBtn}>登录</Button>
                </Space>
            </div>
        </div>
    )
}

export default View